/**
 * eam api router
 * @type {[type]}
 */
var models = require('../../models');
var TopicModel = models.Topic;
var TopicProxy = require('../../proxy/eam');
var UserProxy = require('../../proxy').User;
var UserModel = models.User;
var Reply = require('../../proxy').Reply;
var config = require('../../config');
var eventproxy = require('eventproxy');
var _ = require('lodash');
var at = require('../../common/at');
var renderHelper = require('../../common/render_helper');
var validator = require('validator');
var Q = require('q');
var u = require('util');

exports.get = function(req, res, next) {
    var topicId = req.params.id;
    var mdrender = req.query.mdrender === 'false' ? false : true;

    var ep = new eventproxy();
    ep.fail(next);

    if (topicId) {
        TopicProxy.getFullTopic(topicId, ep.done(function(msg, topic, author, replies) {
            if (!topic) {
                return res.send({
                    error_msg: 'topic_id `' + topicId + '` is not exists.'
                });
            }
            topic = _.pick(topic, ['id', 'author_id', 'eam_wind_turbine_id', 'eam_component_id',
                'eam_root_cause', 'eam_alarm_level', 'eam_maintain_toolkits', 'eam_inspection_assignee',
                'eam_wo_category', 'eam_repair_guide', 'eam_maintain_parts', 'eam_timestamp',
                'eam_wo_id', 'eam_wo_status', 'eam_maintain_from_insp_id', 'eam_report_from_maintain_id',
                'eam_root_cause_insp', 'eam_root_cause_maintain'
            ]);

            if (mdrender) {
                topic.eam_root_cause = renderHelper.markdown(topic.eam_root_cause);
                topic.eam_repair_guide = renderHelper.markdown(topic.eam_repair_guide);
            }
            topic.author = _.pick(author, ['loginname', 'avatar_url']);

            // topic.replies = replies.map(function(reply) {
            //     if (mdrender) {
            //         reply.content = renderHelper.markdown(at.linkUsers(reply.content));
            //     }
            //     reply.author = _.pick(reply.author, ['loginname', 'avatar_url']);
            //     reply = _.pick(reply, ['id', 'author', 'content', 'ups', 'create_at']);
            //     return reply;
            // });
            console.log('get topic --> ' + JSON.stringify(topic));
            res.send(topic);
        }));
    } else {
        res.send({
            error_msg: 'require params.'
        });
    }
}

/**
 * add comments in uplevel workorder
 * the comment lay out the inherited work order id
 * @return {[type]} [description]
 */
function _reply_parent(direction, commentatorId, attachToTopicId ,topic) {
    var ep =  new eventproxy();
    ep.fail(function(err) {
        console.error(err);
    });
    switch (direction) {
        case 'maintenance_to_report':
            Reply.newAndSave(
                u.format('关联 病害报告 <a href="/eam/%s" >%s</a>', topic._id, topic.eam_wo_id),
                attachToTopicId,
                commentatorId,
                null,
                ep.done(function(reply) {
                    console.log('_reply_parent ' + JSON.stringify(reply));
                }));
            break;
        case 'insp_to_maintenance':
            Reply.newAndSave(
                u.format('关联 维修工单 <a href="/eam/%s" >%s</a>', topic._id, topic.eam_wo_id),
                attachToTopicId,
                commentatorId,
                null,
                ep.done(function(reply) {
                    console.log('_reply_parent ' + JSON.stringify(reply));
                }));
            break;
        default:
            console.warn('unknown reply type in _reply_parent');
            break;
    }
}

function _validateEscalation(d) {
    var valid = true;
    var required = [
        "escalation_type",
        "id",
        "eam_alarm_level",
        "eam_component_id",
        "eam_inspection_assignee"
    ];
    required.forEach(function(key) {
        if (!_.has(d, key)) valid = false;
    });

    return valid;
}

function _maintenance_to_report(req, res, next) {
    var deferred = Q.defer();
    var ep = new eventproxy();
    ep.fail(function(err) {
        deferred.reject(err);
    });
    var payload = req.body;
    var tab = 'reports';
    // first get the inspection order by id
    TopicProxy.getFullTopic(payload.id, ep.done(function(msg, topic, author, replies) {
        topic.eam_wo_status = 5;
        topic.save();
        deferred.resolve({
            msg: msg,
            topic: topic,
            author: author,
            replies: replies
        });
    }));
    deferred.promise.then(function(data) {
        //set new Topic as maintenance work order
        var topic = new TopicModel();
        topic.eam_wo_category = tab;
        topic.eam_maintain_from_insp_id = data.topic.eam_maintain_from_insp_id._id;
        topic.eam_report_from_maintain_id = data.topic._id;
        topic.eam_component_id = data.topic.eam_component_id;
        topic.eam_wind_turbine_id = data.topic.eam_wind_turbine_id;
        topic.eam_inspection_assignee = data.topic.eam_inspection_assignee;
        topic.eam_maintain_assignee = data.topic.eam_maintain_assignee;
        topic.eam_maintain_toolkits = payload.eam_maintain_toolkits;
        topic.eam_maintain_parts = payload.eam_maintain_parts;
        topic.eam_repair_guide = payload.eam_repair_guide;
        topic.eam_alarm_level = payload.eam_alarm_level;
        topic.eam_root_cause = payload.eam_root_cause;
        topic.eam_root_cause_maintain = payload.eam_root_cause_maintain;
        // check out status defined in Topic Model
        topic.eam_wo_status = 6;

        // common fields for Topic
        topic.title = 'tiltle placeholder of report';
        topic.content = 'content placeholder of report';
        topic.tab = tab;
        topic.author_id = req.user._id;
        var deferred2 = Q.defer();
        topic.save(function(err, t) {
            if (err) {
                deferred2.reject(err);
            } else {
                _reply_parent('maintenance_to_report', req.user._id, data.topic._id, t);
                deferred2.resolve(t);
            }
        });

        return deferred2.promise;
    }).then(function(report) {
        console.log('saved report');
        console.log(JSON.stringify(report));
        res.status(200).end()
    }).fail(function(err) {
        console.error(err);
        res.send({
            error_msg: err
        });
    });


}


function _insp_to_maintenance(req, res, next) {
    var deferred = Q.defer();
    var ep = new eventproxy();
    ep.fail(function(err) {
        deferred.reject(err);
    });
    var payload = req.body;
    var tab = 'maintenance';
    // first get the inspection order by id
    TopicProxy.getFullTopic(payload.id, ep.done(function(msg, topic, author, replies) {
        topic.eam_wo_status = 2;
        topic.save();
        deferred.resolve({
            msg: msg,
            topic: topic,
            author: author,
            replies: replies
        });
    }));
    deferred.promise.then(function(data) {
        console.log('get insp order ' + JSON.stringify(data));
        //set new Topic as maintenance work order
        var topic = new TopicModel();
        topic.eam_wo_category = tab;
        topic.eam_maintain_from_insp_id = data.topic._id;
        topic.eam_component_id = data.topic.eam_component_id;
        topic.eam_wind_turbine_id = data.topic.eam_wind_turbine_id;
        topic.eam_inspection_assignee = data.topic.eam_inspection_assignee;
        topic.eam_maintain_toolkits = payload.eam_maintain_toolkits;
        topic.eam_maintain_parts = payload.eam_maintain_parts;
        topic.eam_repair_guide = payload.eam_repair_guide;
        topic.eam_alarm_level = payload.eam_alarm_level;
        topic.eam_root_cause = payload.eam_root_cause;
        topic.eam_root_cause_insp = payload.eam_root_cause_insp;
        // check out status defined in Topic Model
        topic.eam_wo_status = 3;

        // common fields for Topic
        topic.title = 'tiltle placeholder of maintenance wo';
        topic.content = 'content placeholder of maintenance wo';
        topic.tab = tab;
        topic.author_id = req.user._id;
        var deferred2 = Q.defer();
        topic.save(function(err, t) {
            if (err) {
                deferred2.reject(err);
            } else {
                deferred2.resolve(t);
                _reply_parent('insp_to_maintenance', req.user._id, data.topic._id, t);
            }
        });
        return deferred2.promise;
    }).then(function(main_wo) {
        console.log('saved maintenance wo');
        console.log(JSON.stringify(main_wo));
        res.status(200).end()
    }).fail(function(err) {
        console.error(err);
        res.send({
            error_msg: err
        });
    });
}

function escalate(req, res, next) {
    /**
     * eam properties
     * @type {[type]}
     */
    var payload = req.body;
    console.log(JSON.stringify(payload));
    if (!_validateEscalation(payload)) {
        res.send({
            error_msg: 'INVALIDE PARAMETERS IN BODY.'
        });
        return;
    }

    switch (payload.escalation_type) {
        case 'maintenance_to_report':
            console.log('maintenance_to_report');
            _maintenance_to_report(req, res, next);
            break;
        case 'insp_to_maintenance':
            console.log('insp_to_maintenance');
            _insp_to_maintenance(req, res, next);
            break;
        default:
            console.log('unknown escalation_type.');
            res.send('unknown escalation_type.');
            break;
    }
};

exports.escalate = escalate;
